from django.shortcuts import HttpResponseRedirect, render_to_response, Http404
from django.template import RequestContext
from django.contrib import messages

from models import *
from functions import RetrieveGrades
from apps.course.models import Course
from apps.course.functions import course_reverse
from apps.participants.models import CourseParticipant

import logging

logger = logging.getLogger('pet.apps.gradebook.views')

# Create your views here.
def index(request, course=None, filters=None):
    logger.debug("course=%s, filters=%s",course,filters)
    TheCourse = Course.find_or_404(course)
    TheUser = request.user
    TheCourseParticipant = CourseParticipant.find(course,user=TheUser)
    
    if not TheCourseParticipant:
        logger.forced_redirect("Anonymous user trying to view grades")
        messages.info(request,"Access to this part of the site requires course authentication");
        return HttpResponseRedirect(course_reverse('course_index',TheCourse))
    
    filter_category = filter_assignment = None
    if filters:
        filters = filters.split('&')
        if len(filters) > 2: logger.http404("Too many filters specified (%s)",len(filters)); raise Http404
        elif len(filters) == 1: filter_category = filters[0]
        elif len(filters) == 2: filter_category = filters[0]; filter_assignment = filters[1]
    Categories, Grades, Metrics = RetrieveGrades(TheCourse, filter_category, filter_assignment)
    TargetCategory = TargetAssignment = None
    CategoryIndex = []

    if Categories and Grades:
        if filter_category:
            TargetCategory = Categories.items()[0][1]['info']
        if filter_assignment:
            temp_categories = Categories.items()[0][1].items()
            TargetAssignment = temp_categories[0][1]['info'] if temp_categories[0][0] != 'info' else temp_categories[1][1]['info']
        for category, assignments in Categories.items():
            Categories[category]['info']['link'] = "%s&" % (Categories[category]['info']['slug'])
            for assignment,sections in assignments.items():
                if assignment == 'info': continue
                Categories[category][assignment]['info']['link'] = "%s&%s" % (Categories[category]['info']['slug'],sections['info']['slug'])
        #for category in Categories:
        #    if category == 'Total': continue
        #    Categories[category]['link'] = None
        #    if not TargetAssignment:
        #        Categories[category]['link'] = "%s&%s" % (TargetCategory['slug'] if TargetCategory else Categories[category]['slug'],
        #                                                  Categories[category]['slug'] if TargetCategory else "")
            
        if TheUser: Grades = {TheUser:Grades[TheUser]}
        if not filter_category and not filter_assignment:
            CategoryIndex = [(x[0],x[1]['info']['number']) for x in Categories.iteritems() if x[0] != 'Total' and x[0] != 'info']
            CategoryIndex = [item[0] for item in sorted(CategoryIndex,key=lambda item: item[1])]
        else:
            CategoryIndex = Categories.keys()
    return render_to_response('gradebook/index.html',{'Grades':Grades,
                                                      'Categories':Categories,
                                                      'Metrics':Metrics,
                                                      'CategoryIndex':CategoryIndex,
                                                      'TargetUser':TheUser,
                                                      'TargetCategory':TargetCategory,
                                                      'TargetAssignment':TargetAssignment},
                              context_instance=RequestContext(request))
